#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#include<errno.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <signal.h>

#define N 32
#define M 256
enum
{
    L=0x1, //登陆
	C,     //聊天
};
typedef struct
{
	int type;
	char name[N];
	char text[M];
}MSG;
#define LEN sizeof(MSG)
int main(int argc,const char *argv[])
{
	int sockfd;
	struct sockaddr_in serveraddr;
	MSG msg;
	pid_t pid;
	socklen_t len=sizeof(struct sockaddr);
    if(argc!=3)
	{
		printf("user:%s ip port",argv[0]);
		return -1;
	}	
	//创建socket
	sockfd = socket(AF_INET,SOCK_DGRAM,0);
	if(sockfd<0)
	{
		perror("socket error");
		exit(-1);
	}
	//指定服务器地址
	bzero(&serveraddr,len);
	serveraddr.sin_family = AF_INET;
	serveraddr.sin_port = htons(atoi(argv[2]));
	serveraddr.sin_addr.s_addr = inet_addr(argv[1]);
	puts("====================client login=================");
	msg.type = L;
	printf("input name:");
	gets(msg.name);
	sendto(sockfd,&msg,LEN,0,(struct sockaddr *)&serveraddr,len);
	//fork--子进程发送，父进程接收
	pid = fork();
	if(pid<0)
	{
		perror("fork errno");
		exit(-1);
	}
	//子进程
	else if(pid == 0)
	{
		while(1)
		{
			gets(msg.text);
			msg.type = C;
			sendto(sockfd,&msg,LEN,0,(struct sockaddr*)&serveraddr,len);
		}
	}
	//父进程
	else
	{
		while(1)
		{
			recvfrom(sockfd,&msg,LEN,0,(struct sockaddr *)&serveraddr,&len);
		}
	}
}